package com.yfproject.service.impl;

import java.util.Set;

import javax.transaction.Transactional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.yfproject.business.CourseRepository;
import com.yfproject.business.StudentRepository;
import com.yfproject.models.Course;
import com.yfproject.models.Student;
import com.yfproject.service.ManyToMany;



@Transactional(rollbackOn=Exception.class)
@Service
public class ManyToManyImpl implements ManyToMany{
	
	@Autowired
	CourseRepository courseRepository;
	
	@Autowired
	StudentRepository studentRepository;
	
	/**
	 * 查学生
	 * @param sId
	 * @return
	 */
	@Override
	public Student findBySid(Integer sid) {
		return studentRepository.findBySid(sid);
	}
	
	/**
	 * 查课程
	 * @param cId
	 * @return
	 */
	@Override
	public Course findByCid(Integer cid) {
		return courseRepository.findByCid(cid);
	}
	
	/**
	 * 选修课程  学生编号 课程编号
	 * @param sid
	 * @param cid
	 */
	@Override
	public void slectingCourse(Integer sid,Integer cid) {
		Student student = findBySid(sid);
		Set<Course> courses = student.getCourse();
		Course course = findByCid(cid);
        courses.add(course);
        student.setCourse(courses);
        studentRepository.save(student);
	}

	@Override
	public void delCourse(Integer sid,Integer cid) {
		Student student = findBySid(sid);
		Set<Course> courses = student.getCourse();
		Course course = findByCid(cid);
		courses.remove(course);
	}

	@Override
	public void insertStu(String name) {
		Student student = new Student();
		student.setStudentName(name);
		studentRepository.save(student);
	}

	@Override
	public void insertCou(String name) {
		Course course = new Course();
		course.setCourseName(name);
		courseRepository.save(course);
		
	}
}
